/**
  * 节流函数：在一定的时间间隔内，只执行一次回调函数
  * @param {Function} callback 回调
  * @param {Number} wait 时间间隔 单位：秒毫
  * @param {Boolean} leading 参数isLeading: 默认{true}表示在计时之前执行 {false}表示在计时之后执行
  * @return {Function}
  */

function throttle(callback, wait, leading = true) {
    var args = null
    var context = null
    var runFlag = false
    var timeout = null
    var isLeading = leading

    var runFn = function () {
        runFlag = true
        callback.apply(context, args)
        timeout = setTimeout(endFn, wait)
        args = null
        context = null
    }

    var endFn = function () {
        timeout = null
        if (!runFlag && !isLeading) runFn()
    }

    var cancelFn = function () {
        var rest = timeout !== null
        if (rest) {
            clearTimeout(timeout)
        }
        args = null
        context = null
        timeout = null
        
        runFlag = false

        return rest
    }

    var throttled = function () {
        runFlag = false
        args = arguments
        context = this
        if (timeout === null) {
            if (isLeading) {
                runFn()
            } else {
                timeout = setTimeout(endFn, wait)
            }
        }
    }

    throttled.cancel = cancelFn

    return throttled
}

module.exports = throttle